package com.hello.facerecognition;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.*;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.*;
import android.widget.Button;
import android.widget.ImageButton;
import com.google.gson.Gson;
import com.hello.facerecognition.Application.BaseApplication;
import com.hello.facerecognition.com.hello.utils.CameraUtils;
import com.hello.facerecognition.com.hello.utils.FileUtils;
import com.hello.facerecognition.com.hello.utils.ImageUtils;
import com.hello.facerecognition.com.hello.utils.StringUtils;
import okhttp3.*;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class Photo extends AppCompatActivity implements SurfaceHolder.Callback, View.OnClickListener {
    public static final Integer REQUEST_CODE_PICK_IMAGE = 101;
    private Button flash;
    private SurfaceView surface;
    private ImageButton shuffer;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    private Button album,back;
    public boolean isBack = false;
    private Handler handler;
    private static final int MSG_AUTOFUCS = 1001;
    AutoFocusCallback autoFocusCallback;
    private Photo photo;
    public Intent data = new Intent();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//没有标题
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//拍照过程屏幕一直处于高亮
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
        setContentView(R.layout.activity_photo);
        shuffer = findViewById(R.id.imageButton4);
        album = findViewById(R.id.button5);
        back = findViewById(R.id.button4);
        flash = findViewById(R.id.button3);
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                Log.v("zzw",""+msg.what);
                switch (msg.what){
                    case MSG_AUTOFUCS:
                        camera.autoFocus(autoFocusCallback);
                        break;
                }
            }
        };
        autoFocusCallback = new AutoFocusCallback();
        autoFocusCallback.setHandler(handler,MSG_AUTOFUCS);
        photo = this;

    }

    @Override
    protected void onStart() {
        super.onStart();
        surface = findViewById(R.id.surfaceView);
        shuffer.setOnClickListener(this);
        album.setOnClickListener(this);
        back.setOnClickListener(this);
        flash.setOnClickListener(this);
        if(surface != null) {
            System.out.println("it's ok");
            surfaceHolder = surface.getHolder();
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//surfaceview不维护自己的缓冲区，等待屏幕渲染引擎将内容推送到用户面前
        }
    }

    @Override
    // apk暂停时执行的动作：把相机关闭，避免占用导致其他应用无法使用相机
    protected void onPause() {
        super.onPause();
        handler.removeCallbacksAndMessages(null);
        camera.setPreviewCallback(null);
        camera.stopPreview();
        camera.release();
        camera = null;
    }

    @Override
    // 恢复apk时执行的动作
    protected void onResume() {
        super.onResume();
        if (null != camera){
            if(isBack){
                camera = CameraUtils.getCameraInstance(BaseApplication.CameraBack);
            }else{
                camera = CameraUtils.getCameraInstance(BaseApplication.CameraFront);
            }
            try {
                setRightCameraOrientation(camera);
                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();
            } catch(IOException e) {
                Log.d("error :", "Error setting camera preview: " + e.getMessage());
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        if(camera == null){
            camera = CameraUtils.getCameraInstance(BaseApplication.CameraFront);
            setRightCameraOrientation(camera);
            try {
                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        refreshCamera();
        setRightCameraOrientation(camera);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        surfaceHolder.removeCallback(this);
        if(camera != null) {
            camera.setPreviewCallback(null);
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    private void setRightCameraOrientation(Camera mCamera) {
        if(camera != null) {
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            int rotation = display.getRotation();
            int degrees = 0;
            switch (rotation) {
                case Surface.ROTATION_0:
                    degrees = 0;
                    break;
                case Surface.ROTATION_90:
                    degrees = 90;
                    break;
                case Surface.ROTATION_180:
                    degrees = 180;
                    break;
                case Surface.ROTATION_270:
                    degrees = 270;
                    break;
            }

            android.hardware.Camera.CameraInfo camInfo =
                    new android.hardware.Camera.CameraInfo();
            android.hardware.Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, camInfo);

            // 这里其实还是不太懂：为什么要获取camInfo的方向呢？相当于相机标定？？
            int result = (camInfo.orientation - degrees + 360) % 360;
            //
            mCamera.setDisplayOrientation(result);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.imageButton4: {
                takePhoto(view);
                break;
            }
            case R.id.button5:{
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");//相片类型
                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                break;
            }
            case R.id.button4:{
                this.finish();
                break;
            }
            case R.id.button3:{
                if(camera != null){
                    camera.release();
                    camera = null;
                }
                if(isBack){
                    camera = CameraUtils.getCameraInstance(BaseApplication.CameraFront);
                    setRightCameraOrientation(camera);
                    try {
                        camera.setPreviewDisplay(surfaceHolder);
                        camera.startPreview();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    isBack = false;
                }else{
                    camera = CameraUtils.getCameraInstance(BaseApplication.CameraBack);
                    setRightCameraOrientation(camera);
                    try {
                        camera.setPreviewDisplay(surfaceHolder);
                        camera.startPreview();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    isBack = true;
                }
                break;
            }
        }

    }

    private void refreshCamera(){
        if (surfaceHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            camera.stopPreview();
        } catch(Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here
        // start preview with new settings
        try {
            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();
            camera.autoFocus(autoFocusCallback);
        } catch (Exception e) {

        }
    }

    public void takePhoto(View view){
        Object[] objects = new Object[]{"/mnt/sdcard/DCIM/camera/face/"};
        TakePhoto takePhoto = new TakePhoto(camera);
        takePhoto.execute(objects);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            Uri uri = data.getData();
            if(uri == null){
                photo.finish();
            }else {
                FormBody builder = new FormBody.Builder()
                        .add("img", ImageUtils.imageToBase64(getPath2uri(this,uri))).build();
                setResult(1000,data.putExtra("uri",getPath2uri(this,uri)));
                Request request = new Request.Builder()
                        .url("http://47.92.246.214:9988/upload.php")
                        .post(builder)
                        .build();
                BaseApplication.okHttpClient.newCall(request).enqueue(new Callback(){
                    @Override
                    public void onFailure(Call call, IOException e) {
                        photo.finish();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String json = response.body().string();
                        Map<String,String> map = null;
                        if(!StringUtils.isNullOrEmpty(json)) {
                            map = new Gson().fromJson(json, Map.class);
                        }
                        String tempPath = map == null ? "" : map.get("file_path");
                        setResult(1000,data.putExtra("file_path",tempPath));
                        photo.finish();
                    }
                });
            }
        }
    }

    public static void saveImage(Bitmap photo, String spath) {
        try {
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(spath, false));
            photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据Uri获取文件的绝对路径，解决Android4.4以上版本Uri转换
     *
     * @param fileUri
     */
    @TargetApi(19)
    public static String getPath2uri(Activity context, Uri fileUri) {
        if (context == null || fileUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, fileUri)) {
            if (isExternalStorageDocument(fileUri)) {
                String docId = DocumentsContract.getDocumentId(fileUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(fileUri)) {
                String id = DocumentsContract.getDocumentId(fileUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(fileUri)) {
                String docId = DocumentsContract.getDocumentId(fileUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[] { split[1] };
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(fileUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(fileUri))
                return fileUri.getLastPathSegment();
            return getDataColumn(context, fileUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(fileUri.getScheme())) {
            return fileUri.getPath();
        }
        return null;
    }

    /**
     * Android4.4 （<19）以下版本获取uri地址方法
     * @param context           上下文
     * @param uri               返回的uri
     * @param selection         条件
     * @param selectionArgs     值
     * @return                  uri文件所在的路径
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String[] projection = { MediaStore.Images.Media.DATA };
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri  The Uri to check.
     * @return
     *      URI权限是否为ExternalStorageProvider
     *      Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri  The Uri to check.
     * @return
     *      URI权限是否为google图片
     *      Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    /**
     * @param uri   The Uri to check.
     * @return
     *      URI权限是否为DownloadsProvider.
     *      Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri  The Uri to check.
     * @return
     *      URI权限是否为MediaProvider.
     *      Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private void showFailRegister(Integer iconId,String title,String message){
        @SuppressWarnings("deprecation")
        AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AppCompat);
        AlertDialog.Builder normalDialog =
                builder;
        normalDialog.setIcon(iconId);
        normalDialog.setTitle(title).setMessage(message);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // ...To-
                    }
                });
        // 创建实例并显示
        normalDialog.create().show();
    }

    class TakePhoto extends AsyncTask {
        private Camera  camera;
        public TakePhoto(Camera camera){
            super();
            this.camera = camera;
        }

        @Override
        protected void onPostExecute(final Object o) {
            super.onPostExecute(o);
            final FormBody builder = new FormBody.Builder()
                    .add("img", ImageUtils.imageToBase64(o.toString())).build();
            setResult(1000,data.putExtra("uri",o.toString()));

            Request request = new Request.Builder()
                    .url("http://47.92.246.214:9988/upload.php")
                    .post(builder)
                    .build();
            BaseApplication.okHttpClient.newCall(request).enqueue(new Callback(){
                @Override
                public void onFailure(Call call, IOException e) {
                    photo.finish();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String json = response.body().string();
                    Map<String,String> map = null;
                    if(!StringUtils.isNullOrEmpty(json)) {
                        map = new Gson().fromJson(json, Map.class);
                    }
                    String tempPath = map == null ? "" : map.get("file_path");
                    setResult(1000,data.putExtra("file_path",tempPath));
                    photo.finish();
                }
            });
        }

        @Override
        protected Object doInBackground(Object[] objects) {
            final String directoryName = (String) objects[0];
            FileUtils.getDiretory(directoryName);
            final String file_path = directoryName +"face_" + System.currentTimeMillis() + ".png";
            camera.takePicture(null, null, new Camera.PictureCallback() {
                @Override
                public void onPictureTaken(byte[] data, Camera camera) {
                    //将字节数组
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    //输出流保存数据
                    try {
                        FileOutputStream fileOutputStream = new FileOutputStream(file_path);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                        camera.stopPreview();
                        camera.startPreview();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });

            return file_path;
        }

    }
}
